﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Vit.Caching;
using Vit.DataAccess;
using Vit.SchemaExplorer.Sql;

namespace Vit.SchemaExplorer
{
    public class DatabaseSchemaFactory
    {
        private static ICacheManager schemaCache;
        public static void SetSchemaCache(ICacheManager cache)
        {
            schemaCache = cache;
        }

        public static DatabaseSchema Create(string connectionStringName)
        {
            var setting = ConfigurationManager.ConnectionStrings[connectionStringName];
            if (setting == null)
                throw new NullReferenceException(string.Format("Can't find connection string setting with name: {0}", connectionStringName));

            return Create(setting.ConnectionString, setting.ProviderName);
        }

        public static DatabaseSchema Create(string connectionString, string providerName)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (string.IsNullOrEmpty(providerName))
                throw new ArgumentNullException("providerName");

            string cacheKey = string.Format("Provider:{0};ConnectionString:{1};", providerName, connectionString);

            if (schemaCache != null && schemaCache.Contains(cacheKey))
                return schemaCache.GetData(cacheKey) as DatabaseSchema;

            IDatabaseSchemaProvider provider = null;
            switch (providerName)
            {
                case "System.Data.SqlClient":
                    provider = new SqlSchemaProvider(connectionString);
                    break;
                case "System.Data.OracleClient":
                    //provider = new SqlSchemaProvider(connectionString);
                    break;
                default:
                    //provider = new SqlSchemaProvider(connectionString);
                    break;
            }

            if (provider == null)
                throw new NullReferenceException("Database Schema Provider should not be null.");

            DatabaseSchema db = new DatabaseSchema(provider, connectionString);
            if (schemaCache != null)
                schemaCache.Add(cacheKey, db);

            return db;
        }
    }
}
